package com.jxust.controller;

import com.jxust.pojo.PageResult;
import com.jxust.pojo.Result;
import com.jxust.pojo.Student;
import com.jxust.pojo.StudentQueryParam;
import com.jxust.service.StuService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/students")
@RestController
public class StuController {
    @Autowired
    private StuService stuService;

    /**
     * 分页查询
     * @param studentQueryParam
     * @return
     */
    @GetMapping
    public Result page(StudentQueryParam studentQueryParam) {
        log.info("分页查询,参数:{}", studentQueryParam);
        try{
            PageResult<Student> pageResult = stuService.page(studentQueryParam);
            log.info("查询成功,数据:{}", pageResult);
            return Result.success(pageResult);
        }catch (Exception e){
            log.error("查询失败", e);
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    /**
     * 批量删除学生信息
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable String ids) {
        log.info("批量删除,参数:{}", ids);
        // 解析字符串为 List<Integer>
        List<Integer> idList = Arrays.stream(ids.split(","))
                .map(Integer::valueOf)
                .collect(Collectors.toList());
        stuService.deleteByIds(idList);
        return Result.success();
    }

    @PostMapping
    public Result save(@RequestBody Student student) {
        log.info("保存学生信息,参数:{}", student);
        stuService.save(student);
        return Result.success();
    }
}
